package com.nbot.server.job;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.nbot.server.domain.KeyParameterDO;
import com.nbot.server.domain.KeyParameterLogDO;
import com.nbot.server.service.KeyParameterLogService;
import com.nbot.server.service.KeyParameterService;
import com.nbot.server.workers.OpcWorker;
import org.jinterop.dcom.common.JIException;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.net.UnknownHostException;
import java.util.List;

/**
 * 重要参数监控任务
 */
@Component
public class KeyParameterJob implements Job {
    private static final Log LOGGER = LogFactory.get();


    @Autowired
    private KeyParameterService keyParameterService;

    @Autowired
    private OpcWorker opcWorker;

    @Autowired
    private KeyParameterLogService keyParameterLogService;

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        LOGGER.info("执行重要参数监控任务");
//获取所有需要查询的点集合
        List<KeyParameterDO> list = keyParameterService.list(null);
        if (list == null) {
            return;
        }
        if (list.isEmpty()) {
            return;
        }
        String val = null;
        for (KeyParameterDO keyParameterDO : list) {
            try {
                //从opc读取数据
                val = opcWorker.readData(keyParameterDO.getItemName());
                //val==""能为true么？？？！！！！
//                if (val==""){
                if (StrUtil.isEmpty(val)) {
                    continue;
                }
                //StaticLog.info("keyParameterDO.getItemName():" + val);
            } catch (JIException e) {
                e.printStackTrace();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            //如果读取成功，就进行保存
            if (val != null && !"".equals(val)) {
                KeyParameterLogDO logDO = new KeyParameterLogDO();
                logDO.setKeyParameterAutoId(keyParameterDO.getAutoId());
                logDO.setKeyParameterValue(BigDecimal.valueOf(Double.parseDouble(val)));
                keyParameterLogService.save(logDO);
               // StaticLog.info("keyParameterLogService.save(logDO):" + logDO);
            }
        }
    }

}